package org.penguin.boot.security.config;

import lombok.extern.slf4j.Slf4j;
import org.penguin.boot.security.provider.PenguinAuthenticationProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;

import javax.annotation.Resource;

@Slf4j
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    private final boolean securityDebug = true;

    @Resource
    private PenguinAuthenticationProvider penguinAuthenticationProvider;

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.debug(securityDebug)
                           .ignoring()
                           .antMatchers("/css/**", "/js/**", "/img/**", "/lib/**", "/webjars/**", "/layui/**", "/favicon.ico", "/myLogin");
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        /*
            DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
            authenticationProvider.setUserDetailsService(userDetailsService);
            authenticationProvider.setPasswordEncoder(passwordEncoder);
            return new ProviderManager(authenticationProvider);
        */
        return new ProviderManager(penguinAuthenticationProvider);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
            //                .antMatchers("/users/**", "/settings/**")
            //                .hasAnyAuthority("Admin", "Editor", "Salesperson", "Shipper")
            //                .anyRequest().authenticated()
            .and().formLogin().usernameParameter("email")
            .loginPage("/loginPage") // 自定义登录页
            .loginProcessingUrl("/login") //登录逻辑
            .failureForwardUrl("/loginPage?error=true") // 登录出错页面
            .successForwardUrl("/user/home") // 登录成功后的页面
            .permitAll()
            .and()
            .rememberMe().key("abCdefgHijklmnopqrstuvxYz0123456789")
            .and()
            .logout()
            .invalidateHttpSession(true)
            .clearAuthentication(true).permitAll();
        return http.build();
    }
}